package com.bmf.module.examination.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmf.module.examination.entity.ExaminationType;
import com.bmf.module.examination.mapper.ExaminationTypeMapper;
import com.bmf.module.examination.service.ExaminationTypeService;
import com.bmf.module.examination.vo.ExaminationTypeCreateVo;
import com.bmf.module.examination.vo.ExaminationTypeResultVo;
import com.bmf.module.testQuestions.entity.QuestionType;
import com.bmf.module.testQuestions.vo.QuestionTypeCreateVo;
import com.bmf.module.testQuestions.vo.TypeResultVo;
import com.bmf.utils.BeanCopyUtils;
import com.bmf.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * (ExaminationType)表服务实现类
 *
 * @author makejava
 * @since 2022-11-29 17:54:33
 */
@Service("examinationTypeService")
public class ExaminationTypeServiceImpl extends ServiceImpl<ExaminationTypeMapper, ExaminationType> implements ExaminationTypeService {

    @Override
    public List<ExaminationTypeResultVo> selectAll() {
        LambdaQueryWrapper<ExaminationType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExaminationType::getCreateId, SecurityUtils.getUserId());
        List<ExaminationType> list = list(wrapper);
        if(CollUtil.isNotEmpty(list)){
            List<ExaminationTypeResultVo> examinationTypeResultVos = BeanCopyUtils.copyBeanList(list, ExaminationTypeResultVo.class);
            return examinationTypeResultVos.stream().filter(s -> s.getParentId() == 0).peek(s -> setChildren(examinationTypeResultVos, s)).collect(Collectors.toList());
        }
        return null;
    }
    private void setChildren(List<ExaminationTypeResultVo> typeResultVos,ExaminationTypeResultVo examinationTypeResultVo){
        List<ExaminationTypeResultVo> childrens = typeResultVos.stream().filter(s -> s.getParentId() == examinationTypeResultVo.getId()).peek(s -> setChildren(typeResultVos, s))
                .collect(Collectors.toList());
        examinationTypeResultVo.setChildrens(childrens);
    }

    @Override
    public Integer insert(ExaminationTypeCreateVo examinationTypeCreateVo) {
        ExaminationType examinationType = BeanCopyUtils.copyBean(examinationTypeCreateVo, ExaminationType.class);
        examinationType.setCreateId(SecurityUtils.getUserId());
        save(examinationType);
        return examinationType.getId();
    }

    @Override
    public Map<Integer,ExaminationType> getByIds(List<Integer> ids) {
        List<ExaminationType> examinationTypes = listByIds(ids);
        if(CollUtil.isEmpty(examinationTypes)){
            return null;
        }
        return examinationTypes.stream().collect(Collectors.toMap(ExaminationType::getId, Function.identity()));
    }
}
